import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,asyncRouters,constantRoutes,someRouter } from '@/router'
import router from "@/router"

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    button:[],
    roles:[],
    routes:[],
    resultAsyncRouters:[],
    finalRouter:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO :(state,userData)=>{
    state.name = userData.name
    state.avatar = userData.avatar
    state.button = userData.buttons
    state.roles = userData.roles
    state.routes = userData.routes
  },
  REALY_ROUTERS :(state,realyRouters)=>{
    state.resultAsyncRouters = realyRouters
    state.finalRouter = constantRoutes.concat(state.resultAsyncRouters,someRouter)
    router.addRoutes(state.finalRouter)
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
      let result = await login({ username: username.trim(), password: password })
      if(result.code == 20000){
      commit('SET_TOKEN',result.data.token);
      
      //本地持久化存储token
      setToken(result.data.token);
        return 'ok';
      }else{
        return Promise.reject(new Error('错误'))
      }
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        //data数据包含 用户名name 用户头像avatar routers返回菜单展示的标记 roles用户角色信息 buttons按钮的信息
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const result = computedAsyncrouter(asyncRouters,state.routes)
        // result.push(constantRoutes,someRouter)
        commit('REALY_ROUTERS',result)
        commit('SET_USERINFO',data)
        resolve(data)
        }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}
const computedAsyncrouter = (rel,asunc)=>{
  const result = rel.filter(item =>{
    if(asunc.indexOf(item.name)){
      if(item.children&&item.children.length > 1){
        item.children = computedAsyncrouter(item.children,asunc)
      }
      return true
    }
  })
  return result
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

